import { computed, shallowReactive } from "vue";
import { createGlobalState } from "@vueuse/core";
import { UI, ParsedResource, Workspace, RawWorkspace } from "@/types";

export const useWorkspace = createGlobalState(() => {
  const rawWorkspaces = shallowReactive<RawWorkspace[]>([]);
  function setRawWorkSpaces(configs: RawWorkspace[]) {
    rawWorkspaces.length = 0;
    rawWorkspaces.push(...configs);
  }

  const workspace = shallowReactive<Workspace>({
    ui: UI.Unknown,
    name: "",
    path: "",
    templates: [],
    components: [],
    regExps: [],
    validators: [],
  });

  function setWorkSpace(ws: Workspace) {
    Object.assign(workspace, ws);
  }

  const idToResourceMap = computed(() => {
    const resources = [
      ...workspace.components,
      ...workspace.regExps,
      ...workspace.validators,
    ];
    return resources.reduce((map, curr) => {
      map[curr.id] = curr;
      return map;
    }, {} as Record<string, ParsedResource>);
  });

  function getResourceById<T extends ParsedResource>(id: string) {
    return idToResourceMap.value[id] as T;
  }

  return {
    workspace,
    setWorkSpace,
    rawWorkspaces,
    setRawWorkSpaces,
    getResourceById,
  };
});
